/*
 * sys_alloc.c
 *
 *  Created on: 2014-3-3
 *      Author: lius
 */

#ifndef SYS_ALLOC_C_
#define SYS_ALLOC_C_
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/mman.h>
#include "sys_alloc.h"

/*
void *mmap(void *start, size_t length, int prot, int flags,int fd, off_t offset);

int munmap(void *start, size_t length);
*/
#define _HEAD_TYPE sys_size_t
#define _HEAD_SIZE sizeof(_HEAD_TYPE)

static unsigned int count = 0, size_sum = 0, min_size = 0xffffffff, max_size = 0;
inline void *sys_malloc (sys_size_t size)
{
	void *ptr = mmap(NULL, size+_HEAD_SIZE,  PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
	if(ptr != MAP_FAILED){
		if(size+_HEAD_SIZE < min_size)
			min_size = size+_HEAD_SIZE;
		if(size+_HEAD_SIZE > max_size)
			max_size = size+_HEAD_SIZE;
		count++;
		size_sum += size+_HEAD_SIZE;
		*(_HEAD_TYPE*)ptr = size;
		return ptr+_HEAD_SIZE;
	}
	printf("%u %s %u %u %u\n", count, strerror(errno), size_sum, min_size, max_size);
	return NULL;
}

inline void sys_free (void *ptr)
{
	_HEAD_TYPE hsize = *(_HEAD_TYPE*)(ptr - _HEAD_SIZE);
	return munmap(ptr - _HEAD_SIZE, hsize);
}


#endif /* SYS_ALLOC_C_ */
